#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <signal.h>       /* for signal */  
#include <execinfo.h>     /* for backtrace() */  
   
extern void signal_handler(int signo);  

#include "tslib.h"

static struct tsdev *ts;
static lv_indev_t *mouse_indev;

static bool tslib_read(lv_indev_drv_t *drv, lv_indev_data_t *data) {
    struct ts_sample sample;
    if (ts_read(ts, &sample, 1) == 1) {
        data->point.x = sample.x;
        data->point.y = sample.y;
        data->state = (sample.pressure > 0) ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
        return false;  // No more data to read
    }
    return false;
}

int tslib_init(void) {
    // 使用 ts_open 手动打开触摸屏设备，必须使用非阻塞方式打开
    ts = ts_open("/dev/input/touchscreen0", 1);
    if (!ts) {
        perror("Failed to open touchscreen device");
        return -1;
    }

    // 配置 tslib（加载校准参数等）
    if (ts_config(ts) < 0) {
        perror("Failed to configure tslib");
        ts_close(ts);
        return -1;
    }
   
}

#define DISP_BUF_SIZE (128 * 1024)

int main(void)
{
    signal(SIGSEGV, signal_handler);  /* 为SIGSEGV信号安装新的处理函数 */

    /*LittlevGL init*/
    lv_init();
    printf("lv init finish\n");
    fflush(stdout);  // 强制刷新标准输出

    /*Linux frame buffer device init*/
    fbdev_init();
    printf("fbdev init finish\n");
    fflush(stdout);  // 强制刷新标准输出

    // 初始化 tslib 输入驱动
    tslib_init();
    printf("tslib init finish\n");
    fflush(stdout);  // 强制刷新标准输出

    /*A small buffer for LittlevGL to draw the screen's content*/
    static lv_color_t buf[DISP_BUF_SIZE];

    /*Initialize a descriptor for the buffer*/
    static lv_disp_draw_buf_t disp_buf;
    lv_disp_draw_buf_init(&disp_buf, buf, NULL, DISP_BUF_SIZE);

    /*Initialize and register a display driver*/
    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.draw_buf   = &disp_buf;
    disp_drv.flush_cb   = fbdev_flush;
    disp_drv.hor_res    = 480;
    disp_drv.ver_res    = 272;
    lv_disp_drv_register(&disp_drv);

    static lv_indev_drv_t indev_drv;
    lv_indev_drv_init(&indev_drv);
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    indev_drv.read_cb = tslib_read;
    mouse_indev = lv_indev_drv_register(&indev_drv);

    /*Set a cursor for the mouse*/
    LV_IMG_DECLARE(mouse_cursor_icon)
    lv_obj_t * cursor_obj = lv_img_create(lv_scr_act()); /*Create an image object for the cursor */
    lv_img_set_src(cursor_obj, &mouse_cursor_icon);           /*Set the image source*/
    lv_indev_set_cursor(mouse_indev, cursor_obj);             /*Connect the image  object to the driver*/

    printf("lvgl init finish \n");
    fflush(stdout);  // 强制刷新标准输出

    /*Create a Demo*/
    lv_demo_widgets();

    /*Handle LitlevGL tasks (tickless mode)*/
    while(1) {
        lv_timer_handler();
        usleep(5000);
    }

    return 0;
}

/*Set in lv_conf.h as `LV_TICK_CUSTOM_SYS_TIME_EXPR`*/
uint32_t custom_tick_get(void)
{
    static uint64_t start_ms = 0;
    if(start_ms == 0) {
        struct timeval tv_start;
        gettimeofday(&tv_start, NULL);
        start_ms = (tv_start.tv_sec * 1000000 + tv_start.tv_usec) / 1000;
    }

    struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    uint64_t now_ms;
    now_ms = (tv_now.tv_sec * 1000000 + tv_now.tv_usec) / 1000;

    uint32_t time_ms = now_ms - start_ms;
    return time_ms;
}
